* ------------------------------------------------------------------------------
* Construct sorting matrices
* ------------------------------------------------------------------------------


* Routines to calculate & store sorting matrices
* ------------------------------------------------------------------------------
		
	cap program drop calcSmx
	program define calcSmx

	* --------------------------------------------------------------------------
	* Inputs: 
	*  - $Ncoh    # cohorts
	*  - $Ns      # education groups
	* --------------------------------------------------------------------------

	{

		* select sample
		keep if married==1
		
		* calculate sorting matrices
		forvalues c=1/$Ncoh {

			preserve
			
			gen inS = 1 if (m$cohvar==`c' & inrange(mage,$a0,$a1)) | (w$cohvar==`c' & inrange(wage,$a0,$a1))
			keep if inS==1
			collapse (percent) inS, by(ms ws) 

			sort ms ws
			mat Smx`c' = J($Ns,$Ns,0)
			local n=0
			forvalues ms=1/$Ns {
			forvalues ws=1/$Ns {
				local n=`n'+1
				mat Smx`c'[`ms',`ws'] = inS[`n']
			}
			}

			restore
			
		}
		
	}	

	end

	
	cap program drop storeSmx
	program define storeSmx
	
	{
		
		drop _all
		set obs $Ncoh
		gen coh = _n
	
		* married
		forvalues ms=1/$Ns {
		forvalues ws=1/$Ns {
			gen Sm`ms'w`ws' = .
			forvalues c=1/$Ncoh {
				replace Sm`ms'w`ws' = Smx`c'[`ms',`ws'] if coh==`c'
			}
		}
		}
		
	}		

	end
	
	
* Calculate sorting matrices
* ------------------------------------------------------------------------------		

	global cohvar "coh10y"
	global Ncoh = 5
	global Ns   = 5
	global a0   = 35
	global a1   = 44
	global storefile "$logfolder\bsSmx.dta"

	* Main estimates
		qui use "$datafolder\cps.dta", replace
		qui calcSmx
		mat Smx50 = Smx3
		mat Smx70 = Smx5
		
	* store estimates
		qui storeSmx
		qui gen rep = 0
		qui save "$storefile", replace
		
	* now bootstrap
		forvalues rep=1/1000 {
			qui use "$datafolder\cps.dta", replace
			qui bsample
			qui calcSmx
			qui storeSmx
			qui gen rep = `rep'
			qui append using "$storefile"
			qui save "$storefile", replace
			di `rep'
		}

	* labels
		qui use "$storefile", replace
		label define coh 1 "1930-39" 2 "1940-49" 3 "1950-59" 4 "1960-69" 5 "1970-75"
		label val coh coh
		label var coh "birth cohort"
		qui save "$storefile", replace
